import { cutFile, CHUNK_SIZE } from './cutFile.js'
import { uploadfileApi, mergeFilesApi } from '@/api/system/index'
import { getFileMD5 } from './createChunk.js'

export default function fileUploadData() {
    // 文件进度条列表
    const fileProgressList = ref([])

    /**
     * 限制用户上传文件的格式和大小
     */
    function handleBeforeUpload(rawFile) {
        if (rawFile.size / 1024 / 1024 > 500) {
            ElMessage.error('上传图片不能大于500MB')
            return false
        }
    }

    /**
     * 上传
     */
    async function handleFileChange(file) {
        console.time('cutFile')
        const FileMd5 = await getFileMD5(file.raw)
        // console.log(FileMd5);

        // 创建一个文件进度条数据
        fileProgressList.value.push({
            uuid: file.uid,
            fileName: file.name,
            percent: 0
        })
        console.log(fileProgressList.value)

        if (file.size > CHUNK_SIZE) {
            uploadChunk(file, FileMd5)
        } else {
            uploadWhole(file, FileMd5)
        }
    }

    // 切片上传
    async function uploadChunk(file, FileMd5) {
        // console.time('cutFile')
        const chunks = await cutFile(file.raw)
        // console.timeEnd('cutFile')
        // console.log(chunks)

        const FileName = file.name
        for (let i = 0; i < chunks.length; i++) {
            // 获取当前文件的进度条数据
            const fileProgress = fileProgressList.value.find(item => item.uuid == file.uid)

            // 获取当前i占总长度的百分比
            const percent = parseInt(((i + 1) / (chunks.length + 1)) * 100)

            try {
                const cut = chunks[i]
                const data = {
                    FileMd5,
                    FileName,
                    IsSliced: true,
                    SubMd5: cut.hash,
                    TotalSlices: chunks.length,
                    SliceIndex: cut.index,
                    SubFileName: cut.hash + '.' + cut.index,
                    file: cut.blob
                }
                const res = await uploadfileApi(data)
                if (res.code == 0) {
                    // 切片上传成功后，更新进度条
                    fileProgress.percent = percent
                    // 循环结束时，调用结束接口
                    if (i == chunks.length - 1) {

                        const endData = {
                            md5: FileMd5,
                            fileName: FileName
                        }
                        const { code, data } = await mergeFilesApi(endData)
                        if (code == 0) {
                            // 整个文件上传成功后，更新进度条
                            fileProgress.percent = 100
                            fileProgress.guid = data.guid
                            fileProgress.filePath = data.filePath

                            ElMessage.success('上传成功')
                            console.timeEnd('cutFile')
                        }
                    }
                }
                if (res.code == 1) {
                    ElMessage.error(res.errMsg)
                    return
                }
            } catch (err) {
                console.log(err)
            }
        }
    }

    // 完整上传
    async function uploadWhole(file, FileMd5) {
        const params = {
            FileMd5,
            FileName: file.name,
            IsSliced: false,
            file
        }
        const fileProgress = fileProgressList.value.find(item => item.uuid == file.uid)
        const { code, data } = await uploadfileApi(params)
        if (code == 0) {
            // 整个文件上传成功后，更新进度条
            fileProgress.percent = 100
            fileProgress.guid = data.guid
            fileProgress.filePath = data.filePath
            console.log(fileProgressList.value)
            ElMessage.success('上传成功')
        }
    }

    return {
        handleBeforeUpload,
        handleFileChange,
        fileProgressList
    }
}
